package com.eastsunsoft.swordfish.ucms.service.impl;

import com.eastsunsoft.swordfish.ucms.base.impl.BaseServiceImpl;
import com.eastsunsoft.swordfish.ucms.dto.UserDTO;
import com.eastsunsoft.swordfish.ucms.entity.User;
import com.eastsunsoft.swordfish.ucms.mapper.UserMapper;
import com.eastsunsoft.swordfish.ucms.service.UserService;
import com.eastsunsoft.swordfish.util.SwBeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;

import java.util.ArrayList;
import java.util.List;

/**
 * <h1>UserServiceImpl</h1>
 * </br>
 *
 * @author donny
 * @date 17/09/2017
 */
@Service
@Transactional
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    private final static Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        super(userMapper);
        this.userMapper = userMapper;
    }

    @Override
    @Transactional(readOnly = true)
    public UserDTO getByAccountAndPwd(String account, String pwd) {
        UserDTO userDTO;
        User user = new User();
        if (account.contains("@")) {
            user.setEmail(account);
        } else if (account.length() == 11) {
            user.setMobile(account);
        } else {
            user.setAccount(account);
        }
        user.setUserpwd(pwd);

        User u = userMapper.selectOne(user);
        if (u == null) {
            // not found
            user.setEmail(account);
            user.setMobile(account);
            user.setAccount(account);
            user.setUserpwd(null);
            Condition condition = new Condition(User.class);
            condition.createCriteria()
                    .andCondition("userpwd = " + pwd
                            + " and (account = '" + account
                            + "' or mobile = '" + account
                            + "' or email = '" + account + "')");
            List<User> users = userMapper.selectByExample(condition);
            if (users.isEmpty() || users.size() > 1) {
                return null;
            }
            u = users.get(0);
        }
        userDTO = new UserDTO();
        SwBeanUtil.copyProperties(u, userDTO);

        return userDTO;
    }

    @Override
    @Transactional(readOnly = true)
    public List<String> listRolesByID(Long id) {
        // TODO 权限获取
        List<String> roles = new ArrayList<>();
        roles.add("UCMS_TESTA:R");
        return roles;
    }
}
